﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WcfBackend;


public partial class ShoppingList : System.Web.UI.Page
{
    private static WcfFoodAndAllergiesClient wcf;
    private static List<Product> shopping = new List<Product>();
    private List<Product> products = new List<Product>();
    HttpCookie listCookie = new HttpCookie("cookiesName");

    protected void Page_Load(object _sender, EventArgs _e)
    {
        wcf = new WcfFoodAndAllergiesClient();

        if (productList.Items.Count == 0 && shoppingList.Items.Count == 0)
        {
            productList.DataSource = products;
            productList.DataBind();
            shoppingList.DataSource = shopping;
            shoppingList.DataBind();
        }
        if (Session["products"] != null)
        {
            listFromRecipe();
            Session["products"] = null;
        }
        if (!IsPostBack)
        {
            GetListOfCookies();
        }
    }

    protected void btnSearchProduct_Click(object _sender, EventArgs _e)
    {
        products.Clear();
        string searchstring = txtSearchProduct.Text;
        products = wcf.GetProductByName(searchstring).ToList();
        productList.DataSource = products;
        productList.DataBind();

    }

    protected void addProduct(object _sender, EventArgs _e)
    {
        LinkButton btn = (LinkButton)(_sender);

        string name = btn.CommandArgument;

        List<Product> tempProducts = wcf.GetProductByName(name).ToList();

        bool found = false;
        int i = 0;
        Product p = null;
        while (!found && i < 30)
        {
            if (tempProducts[i].Name.Equals(name))
            {
                p = tempProducts[i];
                found = true;
            }
            else
            {
                i++;
            }
        }

        shopping.Add(p);


        shoppingList.DataSource = shopping;
        shoppingList.DataBind();


    }

    public void listFromRecipe()
    {
        var myObjectInstance = (List<Product>)Session["products"];
        List<Product> ingredientList = myObjectInstance;
        foreach (Product p in ingredientList)
        {
            shopping.Add(p);

            shoppingList.DataSource = shopping;
            shoppingList.DataBind();
        }
    }

    protected void btnSaveShoppingList_Click(object _sender, EventArgs e)
    {
        string script = "<script type=\"text/javascript\"> CallPrint(shoppingListDiv); </script>";
        ClientScript.RegisterClientScriptBlock(this.GetType(), "myscript", script);
        SaveListAsCookie();

        lblStatus.Visible = true;
        lblStatus.Text = "Indkøbs liste success";
        lblStatus.CssClass = "label-success";
    }

    protected void removeProduct(object _sender, EventArgs _e)
    {
        LinkButton btn = (LinkButton)(_sender);

        int id = Convert.ToInt32(btn.CommandArgument);

        bool done = false;
        int i = 0;

        while (!done)
        {
            if (shopping[i].Id == id)
            {
                shopping.RemoveAt(i);
                done = true;
            }
            else
            {
                i++;
            }
        }

        shoppingList.DataSource = shopping;
        shoppingList.DataBind();
    }

    protected void ProductListView_OnItemCommand(object _sender, ListViewCommandEventArgs _e)
    {

    }

    protected void btnListName_Click(object _sender, EventArgs e)
    {

    }
    private void SaveListAsCookie()
    {
        HttpCookie shListCookie = new HttpCookie("c" + txtListName.Text.Trim());

        if (listCookie["titel"] == null)
        {
            listCookie["titel"] += "c" + txtListName.Text.Trim();

        }
        else
        {
            listCookie["titel"] += ",c" + txtListName.Text.Trim();
        }

        bool first = true;
        for (int i = 0; i < shoppingList.Items.Count; i++)
        {
            if (first)
            {
                string owner = "";
                if (Request.Cookies["userInfo"] != null)
                {
                    owner = Request.Cookies["userInfo"]["userName"];
                }//end if

                shListCookie["listName"] = txtListName.Text;
                shListCookie["listOwner"] = owner;
                shListCookie["listProducts"] = shoppingList.Items[i].ToString();
                first = false;
            }//end if
            else
            {
                shListCookie["listProducts"] += "," + shoppingList.Items[i].ToString();
            }//end else
        }//end for
        Response.Cookies.Add(shListCookie); //Shopping list cookie saved
        Response.Cookies.Add(listCookie); //List cookies saved
    }

    private int GetShoppingListFromCookie(string _selected)
    {                          
        int result = -1; 
        HttpCookie shListCookie = Request.Cookies["c" + _selected];
        List<Product> sList = new List<Product>();
        if (shListCookie != null)
        {
            if (shListCookie["listOwner"].Equals(Request.Cookies["userInfo"]["userName"]))
            {
                string[] p = shListCookie["listProducts"].Split(',');
                foreach (string item in p)
                {
                    sList.Add(wcf.GetProductByName(item).First());
                }
                shoppingList.DataSource = sList;
                shoppingList.DataBind();
                result = 1;
            }
        }
        return result;
    }

    private void GetListOfCookies()
    {
        List<string> cookies = new List<string>();
        if (listCookie["titel"] != null)
        {
            string[] l = listCookie["titel"].Split(',');
            ddlSavedCookies.DataSource = l;
            ddlSavedCookies.DataBind();
        }
        else
        {
            string[] emptyList = { "Tom liste" };
            ddlSavedCookies.DataSource = emptyList;
            ddlSavedCookies.DataBind();
        }
    }
    protected void ddlSavedCookies_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!ddlSavedCookies.SelectedItem.Equals("Tom liste"))
        {
            GetShoppingListFromCookie(ddlSavedCookies.SelectedItem.ToString());
        }
    }
}